var tip = "温馨提示：";
var time = 4000;


var srcElement = null;  
var valueElement = null;  

function showTree(item,valueId,combdtree){ 
	srcElement = item;  
    valueElement = document.getElementById(valueId);  
    var x = getLeft(item);  
    var y = getTop(item) + item.offsetHeight;  
    var w = item.offsetWidth;  
    //blockDTree(x,y,w);
    var show = document.getElementById(combdtree);
    show.style.position = "absolute";
    show.style.left = x;
    show.style.top = y;
    show.style.width = w+20;
    show.style.display = "block"
}

function hiddenDTree(combdtree){  
	var item = document.getElementById(combdtree);  
    if(item){  
         item.style.display = 'none';  
    }  
}

function setSrcValue(text,value,combdtree){
	srcElement.value = text;  
	valueElement.value = value;  
	hiddenDTree(combdtree);  
}

function getTop(e){   
	var offset=e.offsetTop;  
    if(e.offsetParent!=null) offset+=getTop(e.offsetParent);   
    return offset;   
}   
          
function getLeft(e){   
	var offset=e.offsetLeft;   
    if(e.offsetParent!=null) offset+=getLeft(e.offsetParent);   
    	return offset;   
}

//获取栏目树
function getCatalogTree(d,dt,dtree,combdtree,flag){
	$.ajax({
		   type:"post",
		   url:"catalog_tree.json?flag="+flag,
		   async:true,
		   dataType:"json",
		   success:function(result){
			  var msg ='';
			  for(var i = 0;i< result.length; i++){
				msg+=dt+".add('"+result[i].catgId+"','"+result[i].parentCatgId+"','"+result[i].catgName+"','javascript:setSrcValue(\\'"+replaceSpace(result[i].catgName)+"\\',\\'"+result[i].catgId+"\\',\\'"+combdtree+"\\')');\n";
			  }
			  eval(msg);
			  $(dtree).append(d.toString());
			}
	});
}


$(document).ready(function() {
	$("#detail").omButton();
    $("#play").omButton();
    
    
	var make_tab = $('#make-tab').omTabs({});

	var dialog_tab = $("#make-tab").omDialog({
		width: '98%',
		height:480,
		autoOpen : false,
		modal : true,
		resizable : false,
		draggable : false,
		onClose:function(){
			$("#programGrid").omGrid("cancelEdit");
			}
		});
	

	$('#detail').bind('click', function() {
    	var selections=$('#grid').omGrid('getSelections',true);
    	if (selections.length == 0 || selections.length > 1) {
            $.omMessageBox.alert({
                type:'alert',
                title:tip,
                content:'节目集详情至少且只能选择一行记录！'
            });
            return false;
        }
    	showProgramSerialDetail(selections[0].programSeriesId);
    	getProgram();
    	getProgramSerialCatalog();
    	getProgramSerialCheckInfo();
    	getProgramProductContent();
    	dialog_tab.omDialog("option", "title", "节目集详情");
    	dialog_tab.omDialog("open");
    });
})

function showProgramSerialDetail(id){
	$.ajax({
       	type:"post",
       	url:"program_serial_info.json?id="+id,
       	dataType:"json",
      	success:function(msg){
      		var programSeriesName = strSubstring(msg['programSeriesName']);
			$("#programSeriesName").text(programSeriesName);
			$("#programSeriesName").attr('title',msg['programSeriesName']);
			$("#programSeriesAlias").text(msg['programSeriesAlias']);
			$("#englishName").text(msg['englishName']);
			$("#state").text(msg['programStatusName']);
			$("#largePoster").text(msg['poster']);
			$("#definitionTypeName").text(msg['definitionTypeName']);
			$("#language").text(msg['language']);
			$("#terminalType").text(msg['terminalType']);
			$("#programTypeName").text(msg['programType']);
			$("#programClass").text(msg['programClass']);
			$("#programContentType").text(msg['programContentType']);
			$("#years").text(msg['years']);
			$("#tag").text(msg['tag']);
			$("#leadingRole").text(msg['leadingRole']);
			$("#director").text(msg['director']);
			$("#zone").text(msg['zone']);
			$("#scriptWriter").text(msg['scriptWriter']);
			$("#copyright").text(msg['copyright']);
			$("#copyrightProperty").text(msg['copyrightProperty']);
			$("#cpName").text(msg['cpName']);
			$("#subtitle").text(msg['subtitle']);
			$("#spName").text(msg['spName']);
			$("#createDate").text(msg['createDate']);
			$("#lastModifyDate").text(msg['lastModifyDate']);
			$("#premiereDate").text(msg['premiereDate']);
			$("#authEndDate").text(msg['authEndDate']);
			$("#authStartDate").text(msg['authStartDate']);
			$("#syncLiveChannel").text(msg['syncLiveChannel']);
			$("#premiereChannel").text(msg['premiereChannel']);
			$("#stateDate").text(msg['stateDate']);
			$("#programSeriesDesc").text(msg['programSeriesDesc']);
      }
      });
}

function strSubstring(str){
	if(str.length>32){
		return str.substring(0,36);
	}
	return str
}

function playVideo(){
	    dialog_play = $("#play-video").omDialog({
		width: 600,
		height:400,
		autoOpen : false,
		modal : true,
		resizable : false,
		draggable : false,
		onClose:function(){
			$("#play-video").empty();
		}
		});
	var selections = $('#programContentGrid').omGrid('getSelections',true);
	if (selections.length == 0) {
        $.omMessageBox.alert({
            type:'alert',
            title:tip,
            modal:true,
            content:'节目媒体试播至少选择一行记录！'
        });
        return false;
    }
    dialog_play.omDialog("option", "title", "节目媒体试播");
    dialog_play.omDialog("open");
    $("#play-video").empty();
    $("#play-video").append("<center><iframe name='ifa' id='ifa' width='580' height='350' frameborder='0' scrolling='auto' src='play_video.shtml?playUrl="+selections[0].downUrl+"'></iframe></center>");
    
}
function getProgramSerial(){
	$('#grid').omGrid({
    	dataSource : 'program_serial_list.json?op='+$("#op").val(),
    	width : '99%',
        height : 'fit',
        singleSelect : false,
        limit : limit,
        colModel : [ 
					{header : '<b>节目集名称</b>', name : 'programSeriesName', align : 'center', width : 200}, 
					{header : '<b>状态</b>', name : 'state',align : 'center',width: 70},
					{header : '<b>清晰度</b>', name : 'definitionTypeName',align : 'center',width: 70},
					{header : '<b>内容提供商</b>', name : 'cpName',align : 'center',width: 80},
					{header : '<b>节目集类型</b>', name : 'programType',align : 'center',width: 80},
					{header : '<b>节目集小分类</b>', name : 'programClass',align : 'center',width: 100},
					{header : '<b>上映年份</b>', name : 'years',align : 'center',width: 60},
					{header : '<b>导演</b>', name : 'director',align : 'center',width: 120},
					{header : '<b>主演</b>', name : 'leadingRole',align : 'center',width: 120},
					{header : '<b>语言</b>', name : 'language',align : 'center',width: 60},
					{header : '<b>创建时间</b>', name : 'createDate',align : 'center',width: 120},
					{header : '<b>最后更新时间</b>', name : 'lastModifyDate',align : 'center',width: 120},
					{header : '<b>节目集简介</b>', name : 'programSeriesDesc',align : 'center',width: 500}
                     
		]
    });
}
function getProgram(){
    var temporaryName;
	var selections=$('#grid').omGrid('getSelections',true);
	$('#programGrid').omGrid({
    	dataSource : 'program_info.json?id='+selections[0].programSeriesId,
    	width : '99%',
        height : 280,
        singleSelect : false,
        limit : limit,
        colModel : [ 
                     {header : '<b>节目名称</b>', name : "programName", align : 'center', width : 300,editor:{type:"text",editable:true}}, 
                     {header : '<b>排序</b>', name : 'sortNum',align : 'center',width: 60},     
                     {header : '<b>清晰度</b>', name : 'definition',align : 'center',width: 70},
                     {header : '<b>状态</b>', name : 'state',align : 'center',width: 70},
                    /* {header : '<b>剧集</b>', name : 'partNum',align : 'center',width: 60},*/
                     {header : '<b>播放语言</b>', name : 'language',align : 'center',width: 70},
                     /*{header : '<b>文件大小</b>', name : 'fileSize',align : 'center',width: 60},*/
                     {header : '<b>播放时长</b>', name : 'programLength',align : 'center',width: 60},
                     /*{header : '<b>播放地址</b>', name : 'playUrl',align : 'center',width: 150},*/
                     /*{header : '<b>下载地址</b>', name : 'downUrl',align : 'center',width: 150},*/
                     {header : '<b>首播时间</b>', name : 'premiereDate',align : 'center',width: 80},
                     {header : '<b>创建时间</b>', name : 'createDate',align : 'center',width: 120},
                     {header : '<b>最后更新时间</b>', name : 'lastModifyDate',align : 'center',width: 120}     
		],onSuccess : function(){
			$('#programForm').children().height(360);
		},
		onBeforeEdit:function(rowIndex , rowData){
			temporaryName = rowData.programName;
			
	     },
		onAfterEdit:function(rowIndex , rowData){
	        if(temporaryName == rowData.programName){
	        	 $('#programGrid').omGrid("cancelChanges");
	        }else{
	        	if(rowData.programName == ""){
	        		$.omMessageTip.show({title: tip, content: "节目名称不能为空！", timeout: time,type:'error'});
				    $('#programGrid').omGrid("cancelChanges");
	        		return ;
	        	}
				$.post('program_update.shtml',{programId:rowData.programId,programName:rowData.programName},function(result){
				    	if(result=='success'){
				          $.omMessageTip.show({title: tip, content: "节目修改成功！", timeout: time,type:'success'});
				          $('#programGrid').omGrid("saveChanges");
				       }else{
				          $.omMessageTip.show({title: tip, content: "节目修改失败！", timeout: time,type:'error'});
				          $('#programGrid').omGrid("cancelChanges");
				     }
				    
				});
	        }
	     }

    });
}

function getProgramSerialCheckInfo(){
	var selections=$('#grid').omGrid('getSelections',true);
	$('#programSerialCheckInfoGrid').omGrid({
    	dataSource : 'program_serial_check_info.json?id='+selections[0].programSeriesId,
    	width : '99%',
        height : 320,
        singleSelect : true,
        limit : limit,
        colModel : [ 
                     {header : '<b>审核类型</b>', name : 'checkType', align : 'center', width : 100,renderer:function(value){
 						if(value=='first'){return '初审';
						}else{return '终审';}
                      }},
                    
                     {header : '<b>审核时间</b>', name : 'operationTime', align : 'center', width : 120},
                     {header : '<b>审核状态</b>', name : 'state', align : 'center', width : 100,renderer:function(value){
                    	 if(value=='pass'){return '通过';
 						}else{return '不通过';}
                     }},
                     {header : '<b>审核员</b>', name : 'operateName', align : 'center', width : 150},
                     {header : '<b>审核意见</b>', name : 'checkMessage', align : 'center', width : 450}
                     
		],onSuccess : function(){
			$('#programSerialCheckInfoForm').children().height(375);
		}
    });
}
//获取定价信息
function getProgramProductContent(){
	
	var selections=$('#grid').omGrid('getSelections',true);
	$('#programProductContentGrid').omGrid({
    	dataSource : 'program_serial_product_content_info.json?id='+selections[0].programSeriesId,
    	width : '99%',
        height : 320,
        autoFit : true,
        singleSelect : true,
        limit : limit,
        colModel : [ 
                     {header : '<b>产品名称</b>', name : 'productName',align : 'center',width: 200},   
                     {header : '<b>产品类型</b>', name : 'productType', align : 'center', width : 150},
                     {header : '<b>产品价格</b>', name : 'productPrice',align : 'center',width: 150,renderer : function(value) {
                         return value;
                  		}
                     },
                     {header : '<b>创建时间</b>', name : 'createDate',align : 'center',width: 200},
                     {header : '<b>产品描述</b>', name : 'productDesc',align : 'center',width: 200}
		],onSuccess : function(){
			$('#programProductContentForm').children().height(375);
		}
    });
}

function getProgramSerialCatalog(){
	var selections=$('#grid').omGrid('getSelections',true);
	$('#programSerialCatalogGrid').omGrid({
    	dataSource : 'find_program_serial_catalog_by_pid.json?id='+selections[0].programSeriesId,
    	width : '99%',
        height : 320,
        singleSelect : true,
        limit : [0],
        colModel : [ 
                     {header : '<b>栏目名称</b>', name : 'catgName', align : 'center', width : 180}, 
                     {header : '<b>上级栏目</b>', name : 'parentName', align : 'center', width : 180},
                     {header : '<b>栏目状态</b>', name : 'catalogStatusName',align : 'center',width: 60},
                     {header : '<b>子栏目风格</b>', name : 'childStyleName',align : 'center',width: 70},
                     {header : '<b>位置</b>', name : 'seqId',align : 'center',width:40},
                     {header : '<b>栏目类型</b>', name : 'catgTypeName',align : 'center',width: 80},
                     {header : '<b>描述</b>', name : 'catgDesc',align : 'center',width: 300}
                     
		],onSuccess : function(){
			$('#programSerialCatalogForm').children().height(375);
		}
    });
}


function showLargePoster()
{
	var imgAddress = $("#largePoster").text();
	var background = $("<div></div>");
	$(background).attr("id","overlaybackground").animate({'opacity':'.6'},6).css({
	  "width"  : '100%','height' : '100%','background' : '#656565','z-index' : '5000',
	  'position': 'absolute','top' : '0px','left' : '0px'
	});
	$("body").append(background);
	var newimage = $("<img style='cursor: pointer;' src='"+imgAddress+"'/>");
	var width = $('body').width();
	$(newimage).attr("id","largeimage").css({
	'left' : '40%','top' : '20%','position': 'absolute','z-index' : '5000','display' : 'none',
	'border' : '1px solid #fff'
	});
	$("body").append(newimage);
	$("#largeimage").fadeIn(300,function(){
	  $(this).click(function(){
	       $(this).fadeOut(300);
	         $("div#overlaybackground").fadeOut(300,function(){
	            $("#overlaybackground").remove();
	            $("#largeimage").remove();
	         })
	     })
	})
}
function changeState(state){
    var selections=$('#grid').omGrid('getSelections',true);
	var toDeleteRecordID = "";
	for(var i=0;i<selections.length;i++){
    	if(i != selections.length - 1){
    		toDeleteRecordID  += selections[i].programSeriesId+",";
        }else{
        	toDeleteRecordID  += selections[i].programSeriesId;
        }
    }
    $.post('rollback_submit.shtml',{ids:toDeleteRecordID,destinationStatus:state,},function(result){
        $('#grid').omGrid('reload');
        if(result=='success'){
         	$.omMessageTip.show({title: tip, content: "节目集回退成功！", timeout: time,type:'success'});
         }else{
         	$.omMessageTip.show({title: tip, content: "节目集回退失败！", timeout: time,type:'error'});
         }
        $('#dialog-form-back').omDialog('close');
    });
}

function programSerialBack()
{
	var dialog_back = $("#dialog-form-back").omDialog({width: 250,autoOpen : false,modal : true,resizable : false,draggable : false});
    $('#roll').bind('click', function() {
    	var selections=$('#grid').omGrid('getSelections',true);
    	if (selections.length == 0) {
            $.omMessageBox.alert({type:'alert',title:'温馨提示',content:'请至少选择一条需要回退的节目集！'});
            return false;
        }
    	//加入分发中状态剔除
    	for(var i=0;i<selections.length;i++){
	    	if("分发中" == selections[i].programStatusName){
	    		 $.omMessageBox.alert({
		                type:'alert',
		                title:tip,
		                content:'节目集：《'+selections[i].programSeriesName+'》<br/>分发中，不能回退！'
		            });
				return false;
	        }
    	}
    	
        $.post('rollback_status.shtml',{id:selections[0].programSeriesId},function(result){
            if(result.status=='prm'){
            	var nodes = result.pdNodes;
            	$.each(nodes,function(){
            		$("."+this).hide();
            	});
             }else if(result.status=='error'){
            	 alert("数据错误");
            	 return;
             }
            dialog_back.omDialog("option", "title", "节目集回退");
            dialog_back.omDialog("open");
        });
       
    });
}

function cis_programSerialInfo(id){
	$.dialog({
		id: 'LHG2012D',
		width: '980px',
		height: '500px',
		title: '节目集详细信息',
		drag: false,
		max: false,
		min: false,
		lock:true,
    content: 'url:common_data_info.shtml?id='+id
});
}

//限制textarea输入长度，在需要用到页面的初始化方法中调用该方法即可
function limit_textarea_input() {   
	$("textarea[maxlength]").bind('input propertychange', function() {   
			var maxLength = $(this).attr('maxlength');   
			if ($(this).val().length > maxLength) {   
				$(this).val($(this).val().substring(0, maxLength));   
			}   
			})   
		}
//比较两个日期的大小
function compareDate(d1,d2){
	if(d1 && d2){
	   return ((new Date(d1.replace(/-/g,"\/"))) >= (new Date(d2.replace(/-/g,"\/"))));
	}
	return true
}
//日期相差的天数
function DateDiff(sDate1,sDate2){
	   var aDate,oDate1,oDate2,iDays ;
	   aDate =sDate1.split('-');
	   oDate1 = new Date(aDate[1]+'-'+aDate[2]+'-'+aDate[0]) ;
	   //转换为04-19-2007格式
	   aDate = sDate2.split('-');
	   oDate2 = new Date(aDate[1]+'-'+ aDate[2] +'-'+aDate[0]);
	   iDays = parseInt(Math.abs(oDate1 -oDate2)/1000/60/60/24);//把相差的毫秒数转换为天数
	   return iDays ;
	   }

function replaceSpace(str){
	return str.replace(/\s/g,'%20');   
}

